package com.example.zelonghu.test_sensor;

import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private SensorManager sm;
    Sensor proximitySensor = null;
    SensorEventListener proximitySensorListenser = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        proximitySensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        if(proximitySensor == null){
            Toast.makeText(this,"接近传感器不可用",Toast.LENGTH_LONG).show();
            finish();
        }
         proximitySensorListenser = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                if(sensorEvent.values[0] < proximitySensor.getMaximumRange()){
                    //有物体
                    getWindow().getDecorView().setBackgroundColor(Color.RED);
                }else{
                    //没发生
                    getWindow().getDecorView().setBackgroundColor(Color.BLUE);
                }

            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {

            }
        };



    }

    @Override
    protected void onResume() {
        super.onResume();
        sm.registerListener(proximitySensorListenser,proximitySensor,2 * 1000 * 1000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sm.unregisterListener(proximitySensorListenser);
    }
}
